package top.dimples.service.impl;

import cn.hutool.core.lang.UUID;
import com.wf.captcha.ChineseGifCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.dimples.common.ApiResponse;
import top.dimples.service.CaptchaService;

import java.time.Duration;
import java.util.HashMap;

/**
 * @author Dimples_YJ
 * @date 2021/12/5
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 验证码生成
     *
     * @return 二维码生成结果
     */
    @Override
    public ApiResponse generateCode() {
        ChineseGifCaptcha captcha = new ChineseGifCaptcha(130, 48);
        String key = UUID.randomUUID(true).toString();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("img", captcha.toBase64());
        hashMap.put("key", key);
        redisTemplate.opsForValue().set(key,captcha.text(), Duration.ofMinutes(1));
        return ApiResponse.ofSuccess(hashMap);
    }

    /**
     * 验证验证码
     *
     * @param key 验证码的 key
     * @param code 验证码的 code
     * @return 验证码是否正确
     */
    @Override
    public Boolean validateCode(String key, String code) {
        String oCode = redisTemplate.opsForValue().get(key);
        return code.equals(oCode);
    }

    /**
     * 删除验证码
     *
     * @param key 验证码的 key
     * @return 是否删除成功
     */
    @Override
    public Boolean removeCode(String key) {
        return redisTemplate.delete(key);
    }
}
